<template>
  <div class="p-2 container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="任务名称" prop="patrolTaskName">
              <el-input v-model="queryParams.patrolTaskName" placeholder="请输入巡视任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
             <el-form-item label="创建时间" prop="">
              <el-date-picker v-model="queryParams.startAndEnd" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" style="flex: 1; display: flex; flex-direction: column; position: relative;">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['camera:camera-patrol-task:add']" type="primary" plain @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['camera:camera-patrol-task:remove']" type="danger" plain :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['admin']" type="warning" plain @click="generateDailyPatrolTask()">下发任务</el-button>
          </el-col>

          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="cameraPatrolTaskList" style="flex: 1;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="巡视任务编码" align="center" prop="patrolTaskCode" min-width="200" show-overflow-tooltip />
        <el-table-column label="巡视任务名称" align="center" prop="patrolTaskName" min-width="180" show-overflow-tooltip />
        <el-table-column label="巡视任务路线" align="center" prop="patrolRouteName" min-width="180" show-overflow-tooltip />
        <el-table-column label="任务周期" align="center" prop="patrolRouteName" min-width="220" show-overflow-tooltip >
          <template #default="scope">
            {{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }} ～ {{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="cameraPatrolTaskStatus">
          <template #default="scope">
            <dict-tag :options="camera_patrol_task_status" :value="scope.row.cameraPatrolTaskStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="执行人" align="center" prop="executeUserName" min-width="120" show-overflow-tooltip />
        <el-table-column label="创建人" align="center" prop="createByName" min-width="120" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150px">
          <template #default="scope">
            <el-button v-if="scope.row.cameraPatrolTaskStatus==1" link type="primary" @click="handleClose(scope.row)">停用</el-button>
            <el-button v-if="scope.row.cameraPatrolTaskStatus==0" link type="primary" @click="handleOpen(scope.row)">启用</el-button>
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button v-hasPermi="['camera:camera-patrol-task:remove']" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加或修改巡视任务对话框 -->
    <el-drawer v-model="dialog.shouAdd" :title="dialog.title" width="500px" append-to-body destroy-on-close size="820px">
      <add @close="dialog.shouAdd = false" @success="getList" />
    </el-drawer>
    <!-- 详情巡视任务对话框 -->
    <el-drawer v-model="dialogDetail.shouAdd" :title="dialogDetail.title" size="820px" append-to-body destroy-on-close>
      <detail :camera-patrol-task-id="cameraPatrolTaskId" @close="dialogDetail.shouAdd = false" @success="getList" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import {
  listcameraPatrolTask,
  delcameraPatrolTask,
  updatecameraPatrolTask,
  updatecameraPatrolTaskeditStatus
} from '@/api/security/video-patrol/camera-patrol-task';
import { cameraPatrolTaskVO, cameraPatrolTaskQuery, cameraPatrolTaskForm } from '@/api/security/video-patrol/camera-patrol-task/types';
import add from './components/add.vue';
import detail from './components/detail.vue';
import request from '@/utils/request'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { camera_patrol_task_status, clock_flag } = toRefs<any>(proxy?.useDict('camera_patrol_task_status', 'clock_flag'));

const cameraPatrolTaskList = ref<cameraPatrolTaskVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogDetail = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: cameraPatrolTaskForm = {
  cameraPatrolTaskId: undefined,
  remark: undefined,
  patrolTaskName: undefined,
  executeRoleId: undefined
}
const data = reactive<PageData<cameraPatrolTaskForm, cameraPatrolTaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patrolTaskName: undefined,
    executeRoleId: undefined,
    startAndEnd: undefined,
    params: {
    }
  },
  rules: {
    patrolTaskName: [] }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询巡视任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listcameraPatrolTask(queryParams.value);
  cameraPatrolTaskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.startAndEnd = undefined;
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: cameraPatrolTaskVO[]) => {
  ids.value = selection.map(item => item.cameraPatrolTaskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  dialog.shouAdd = true;
  dialog.title = '添加巡视任务';
}

/** 删除按钮操作 */
const handleDelete = async (row?: cameraPatrolTaskVO) => {
  const _cameraPatrolTaskIds = row?.cameraPatrolTaskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除巡视任务编号为"' + _cameraPatrolTaskIds + '"的数据项？').finally(() => loading.value = false);
  await delcameraPatrolTask(_cameraPatrolTaskIds)
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('camera/camera-patrol-task/export', {
    ...queryParams.value
  }, `camera-patrol-task_${new Date().getTime()}.xlsx`)
}

/** 停用 */
const handleClose = async(row)=>{
  Object.assign(form.value, row);
  form.value.cameraPatrolTaskId = row.cameraPatrolTaskId
  form.value.cameraPatrolTaskStatus = '0'
  const res = await updatecameraPatrolTaskeditStatus(form.value)
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功');
    await getList()
  } else {
    proxy?.$modal.msgError(res.msg)
  }
}

/** 启用 */
const handleOpen = async(row)=>{
  Object.assign(form.value, row);
  form.value.cameraPatrolTaskStatus = '1'
  const res = await updatecameraPatrolTaskeditStatus(form.value)
  proxy?.$modal.msgSuccess('操作成功');
  getList()
}

/** 详情dialog */
const cameraPatrolTaskId = ref()
const handleDetail = async(row) =>{
  cameraPatrolTaskId.value = row?.cameraPatrolTaskId || ids.value[0]
  dialogDetail.shouAdd = true;
  dialogDetail.title = '巡视任务详情';
}

/**
 * 下发任务
 */
const generateDailyPatrolTask = async ()=> {
  await proxy?.$modal.confirm('是否确认下发巡视任务？').finally(() => {});

  proxy.$modal.loading('正在下发，请稍候');
  let res = await request({ url: '/camera/camera-patrol-task/generate-daily-patrol-task', method: 'post' }).finally(() => proxy.$modal.closeLoading())
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('下发成功');
    await getList()
  } else {
    proxy?.$modal.msgError(res.msg)
  }
}

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.el-card__header) {
    height: 60px;
}
:deep(.el-card__body) {
    height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}
:deep(.pagination-container) {
    margin-top: 0;
}
::v-deep .el-table__header-wrapper .el-table__header .el-checkbox {
  display: none;
}
</style>
